package com.kexio.log.analytics.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;

import com.kexio.log.analytics.adapter.LoggingAspectAdapter;
import com.kexio.log.analytics.adapter.PerformanceMonitorAdapter;
import com.kexio.log.analytics.service.LogAnalyticsService;
import com.kexio.log.analytics.service.impl.LogAnalyticsServiceImpl;
import com.kexio.log.analytics.service.impl.LogMetricsCollectorImpl;
import com.kexio.log.analytics.service.impl.PerformanceAnalyzerImpl;

/**
 * 日志分析自动配置
 * 
 * 当启用日志分析时，自动配置相关的Bean和组件
 * 
 * @author Kexio Team
 * @since 1.0.0
 */
@Configuration
@ConditionalOnProperty(prefix = "kexio.log.analytics", name = "enabled", havingValue = "true")
@EnableConfigurationProperties(LogAnalyticsProperties.class)
@ComponentScan(basePackages = "com.kexio.log.analytics")
@EnableScheduling
public class LogAnalyticsAutoConfiguration {
    
    private static final Logger logger = LoggerFactory.getLogger(LogAnalyticsAutoConfiguration.class);
    
    /**
     * 日志指标收集器
     */
    @Bean
    @ConditionalOnMissingBean
    public LogMetricsCollectorImpl logMetricsCollector() {
        logger.info("注册日志指标收集器: LogMetricsCollectorImpl");
        return new LogMetricsCollectorImpl();
    }
    
    /**
     * 性能分析器
     */
    @Bean
    @ConditionalOnMissingBean
    public PerformanceAnalyzerImpl performanceAnalyzer() {
        logger.info("注册性能分析器: PerformanceAnalyzerImpl");
        return new PerformanceAnalyzerImpl();
    }
    
    /**
     * 日志分析服务
     */
    @Bean
    @ConditionalOnMissingBean
    public LogAnalyticsService logAnalyticsService(LogMetricsCollectorImpl metricsCollector,
                                                   LogAnalyticsProperties properties) {
        logger.info("注册日志分析服务: LogAnalyticsServiceImpl");
        return new LogAnalyticsServiceImpl();
    }
    
    /**
     * LoggingAspect 适配器
     * 
     * 当存在 LoggingAspect 类时才创建
     */
    @Bean
    @ConditionalOnMissingBean
    @ConditionalOnClass(name = "com.kexio.auth.aop.LoggingAspect")
    public LoggingAspectAdapter loggingAspectAdapter() {
        logger.info("注册 LoggingAspect 适配器: LoggingAspectAdapter");
        LoggingAspectAdapter adapter = new LoggingAspectAdapter();
        adapter.initialize();
        return adapter;
    }
    
    /**
     * PerformanceMonitorAspect 适配器
     * 
     * 当存在 PerformanceMonitorAspect 类时才创建
     */
    @Bean
    @ConditionalOnMissingBean
    @ConditionalOnClass(name = "com.kexio.auth.aop.PerformanceMonitorAspect")
    public PerformanceMonitorAdapter performanceMonitorAdapter() {
        logger.info("注册 PerformanceMonitorAspect 适配器: PerformanceMonitorAdapter");
        PerformanceMonitorAdapter adapter = new PerformanceMonitorAdapter();
        adapter.initialize();
        return adapter;
    }
    
    /**
     * 日志分析启动日志
     */
    @Bean
    public LogAnalyticsStartupLogger logAnalyticsStartupLogger(LogAnalyticsProperties properties) {
        return new LogAnalyticsStartupLogger(properties);
    }
    
    /**
     * 启动日志组件
     */
    public static class LogAnalyticsStartupLogger {
        
        private final LogAnalyticsProperties properties;
        
        public LogAnalyticsStartupLogger(LogAnalyticsProperties properties) {
            this.properties = properties;
            logStartupInfo();
        }
        
        private void logStartupInfo() {
            logger.info("========================================");
            logger.info("📊 Kexio Log Analytics 启动成功!");
            logger.info("🔍 分析功能配置:");
            logger.info("   性能分析: {}", properties.getAnalysis().isEnablePerformance() ? "✅ 启用" : "❌ 禁用");
            logger.info("   错误分析: {}", properties.getAnalysis().isEnableError() ? "✅ 启用" : "❌ 禁用");
            logger.info("   用户行为分析: {}", properties.getAnalysis().isEnableUserBehavior() ? "✅ 启用" : "❌ 禁用");
            logger.info("⚠️ 告警配置:");
            logger.info("   错误率阈值: {}%", properties.getAlert().getErrorRateThreshold() * 100);
            logger.info("   慢请求阈值: {}ms", properties.getAlert().getSlowRequestThreshold());
            logger.info("📋 报告配置:");
            logger.info("   自动生成: {}", properties.getReport().isAutoGenerate() ? "✅ 启用" : "❌ 禁用");
            logger.info("   每日报告: {}", properties.getReport().isDailyReport() ? "✅ 启用" : "❌ 禁用");
            logger.info("   每周报告: {}", properties.getReport().isWeeklyReport() ? "✅ 启用" : "❌ 禁用");
            logger.info("🎯 数据保留:");
            logger.info("   原始日志: {}天", properties.getRetention().getRawLogsDays());
            logger.info("   聚合数据: {}天", properties.getRetention().getAggregatedDataDays());
            logger.info("   报告: {}天", properties.getRetention().getReportsDays());
            logger.info("🔗 管理接口: /api/log/analytics/*");
            logger.info("========================================");
        }
    }
}
